package com.java.basis.reference;

import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.util.concurrent.TimeUnit;

/**
 * @author wangning
 * @date 2023/5/18 16:34
 * 引用队列
 */
public class ReferenceQueueDemo {
    public static void main(String[] args) {
        Object obj = new Object();
        ReferenceQueue<Object> referenceQueue = new ReferenceQueue<>();
        WeakReference<Object> weakReference = new WeakReference<>(obj, referenceQueue);
        System.out.println(obj);
        System.out.println(weakReference.get());
        System.out.println(referenceQueue.poll());
        System.out.println("=========");
        obj = null;
        System.gc();
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(obj);
        System.out.println(weakReference.get());
        System.out.println(referenceQueue.poll());
        //java.lang.Object@5b6f7412
        //java.lang.Object@5b6f7412
        //null
        //=========
        //null
        //null
        //java.lang.ref.WeakReference@27973e9b
    }
}
